﻿//////////////////////////////////////////////////////////////////////////
/// Copyright (C), 1998-2016, rytec Corporation. All rights reserved.
/// \file       FilterWidget.cpp
/// \brief      
/// \author     wyf
/// \version    0.95
/// \date       2020-9
//////////////////////////////////////////////////////////////////////////

#include "FilterWidget.h"

#include <QStandardItemModel>
#include <QListView>
#include <QHBoxLayout>
#include <QPainter>

CRyFilterWidget::CRyFilterWidget(QWidget* parent)
    : QWidget(parent)
    , mSection(-1)
    , mListView(NULL)
{
    setMaximumHeight(300);
    setWindowFlags(Qt::Popup | Qt::FramelessWindowHint);

    QHBoxLayout* mainLayout = new QHBoxLayout(this);
    mainLayout->setMargin(1);
    setLayout(mainLayout);

    mListView = new QListView(this);
    mListView->setEditTriggers(QAbstractItemView::NoEditTriggers);
    mListView->setSelectionMode(QAbstractItemView::SingleSelection);
    mListView->setSelectionBehavior(QAbstractItemView::SelectRows);
    mListView->setModel(new QStandardItemModel(mListView));
    mainLayout->addWidget(mListView);

    connect(mListView, &QAbstractItemView::clicked, this, &CRyFilterWidget::onItemCliked);
}

void CRyFilterWidget::getFilterData(QStringList& texts, QList<bool>& checkStates) const
{
    QStandardItemModel* itemModel = (QStandardItemModel*)mListView->model();
    for (int i = 0; i < itemModel->rowCount(); i++)
    {
        QStandardItem* item = itemModel->item(i, 0);
        checkStates.push_back(item->checkState() == Qt::Checked);
        texts.push_back(item->text());
    }
}

void CRyFilterWidget::setFilterData(const QStringList& texts, const QList<bool>& checkStates)
{
    if (texts.size() != checkStates.size())
        return;

    QStandardItemModel* itemModel = (QStandardItemModel*)mListView->model();
    itemModel->clear();

    QStringList::ConstIterator cit1 = texts.begin();
    QList<bool>::ConstIterator cit2 = checkStates.begin();
    for (; cit1 != texts.end(); ++cit1, ++cit2)
    {
        QStandardItem* item = new QStandardItem(*cit1);
        item->setCheckState(*cit2 ? Qt::Checked : Qt::Unchecked);
        itemModel->appendRow(item);
    }
}

void CRyFilterWidget::onItemCliked(const QModelIndex& index)
{
    QStandardItemModel* itemModel = (QStandardItemModel*)mListView->model();
    QStandardItem* item = itemModel->itemFromIndex(index);
    if (NULL == item)
        return;

    item->setCheckState((item->checkState() == Qt::Checked) ? Qt::Unchecked : Qt::Checked);
}

void CRyFilterWidget::hideEvent(QHideEvent* event)
{
    QWidget::hideEvent(event);
    emit filterFinished();
}
